<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" />
    <h1></h1>
    <button>按钮</button>
  </body>
  <script>
    const input = document.getElementsByTagName("input")[0];
    const h1 = document.getElementsByTagName("h1")[0];
    const btn = document.getElementsByTagName("button")[0];
    var data = {
      text: "",
    };

    //vue2实现
    // input.addEventListener("input", function (e) {
    //   data.text = e.target.value;
    //   console.log(data)
    // });

    // btn.onclick = function () {
    //   data.text = "你好啊";
    // };

    // Object.defineProperty(data, "text", {
    //   get: function () {
    //     return data["text"];
    //   },
    //   set: function (newValue) {
    //     input.value = newValue;
    //     h1.innerText = newValue;
    //   },
    // });


    //vue3实现
    function effect() {
      h1.innerText = data.text;
    }

    const obj = new Proxy(data, {
      get: function (target, key) {
        return target[key];
      },
      set: function (target, key, newValue) {
        target[key] = newValue;
        effect();
        return true;
      },
    });

    input.addEventListener("input", function (e) {
      obj.text = e.target.value;
    });

    btn.onclick = function () {
      obj.text = "你好啊";
    };
  </script>
</html>
